//
//  BTCursor.swift
//  BusinessToolkit
//
//  Created by JY_NEW on 2021/11/2.
//

import Foundation

/// 游标，线程安全，可用在多线程遍历索引，可保证每次取的索引不会重复或遗漏
public struct BTCursor {
    private let _queue = DispatchQueue(label: "business toolkit curso queue", attributes: .concurrent)
    private var _value: Int
    /// 最大值，为空则不限
    public let max: Int?
    public init(_ value: Int = 0, max: Int? = nil) {
        self._value = value
        self.max = max
    }
    /// 重置
    public mutating func reset(_ value: Int = 0) {
        _queue.sync(flags: .barrier) { _value = value }
    }
    /// 获取值
    public func value() -> Int {
        return _queue.sync { _value }
    }
    /// 获取值并+1，若超过最大值则返回nil，通过该方法遍历值
    public mutating func move() -> Int? {
        return _queue.sync(flags: .barrier) {
            if let max = max, _value > max {
                return nil
            }
            let v = _value
            _value += 1
            return v
        }
    }
}
